import OpenAI from "openai";
import type { ChatCompletion, ChatCompletionMessageParam, ChatCompletionTool } from "openai/resources/chat/completions";
import { Message } from "@/app/shared/types/message";
export const runtime = "edge";
export const maxDuration = 30;

const llm = new OpenAI({
  apiKey: process.env.OPENAI_API_KEY || 'sk-8f1676c9118b486889c3de773ca72633',
  baseURL: process.env.OPENAI_BASE_URL || 'https://api.deepseek.com/v1',
});

const model_name = process.env.OPENAI_MODEL || "deepseek-chat";


export async function POST(req: Request): Promise<Response> {
  // return ChatCompletion
  const { messages, tools } = await req.json();

  // messages 是 Message 类型
  const messages_array = messages.map((message: Message) => ({
    role: message.role,
    content: message.content
  }));

  console.log("messages_array:", messages_array);

  // tools是ChatCompletionTool[]类型
  let tools_array: ChatCompletionTool[] = [];
  if(tools) {
    tools_array = tools.map((tool: ChatCompletionTool) => ({
      type: tool.type,
      function: tool.function
    }));
  }

  let response: ChatCompletion;
  if(tools_array.length > 0) {
    // tool调用
    response = await llm.chat.completions.create({
      model: model_name,
      messages: messages_array,
      tools: tools_array,
      tool_choice: "auto",
    })
  } else {
    // 普通聊天
     response = await llm.chat.completions.create({
      model: model_name,
      messages: messages_array,
      max_tokens: 1000,
    })
  }

  return new Response(JSON.stringify(response), {
    status: 200,
    headers: {
      'Content-Type': 'application/json'
    },
  })
}
// export async function POST(req: Request) {
//   const { messages, system, tools } = await req.json();

//   const result = streamText({
//     model: openai("gpt-4o"),
//     messages,
//     // forward system prompt and tools from the frontend
//     system,
//     tools: Object.fromEntries(
//       Object.entries<{ parameters: unknown }>(tools).map(([name, tool]) => [
//         name,
//         {
//           parameters: jsonSchema(tool.parameters!),
//         },
//       ]),
//     ),
//   });

//   return result.toDataStreamResponse();
// }
